package org.mspring.mlog.security.remember;

import org.mspring.mlog.entity.User;
import org.mspring.mlog.security.SecurityKeys;
import org.mspring.mlog.security.service.UserService;
import org.mspring.mlog.security.user.UserDetailsImpl;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Gao Youbo
 * @since 2014-09-10 17:42:01
 */
public class RememberMeService extends TokenBasedRememberMeServices implements LogoutHandler {

    private UserService userService;

    public RememberMeService(String key, UserDetailsService userDetailsService) {
        super(key, userDetailsService);
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Override
    protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request, HttpServletResponse response) {
        UserDetails userDetails = super.processAutoLoginCookie(cookieTokens, request, response);
        if (userDetails != null) {
            User user = getUser(userDetails);
            if (user != null && !user.getDeleted()) {
                // 将User对象保存到Session中
                request.getSession().setAttribute(SecurityKeys.CURRENT_USER, user);
            }
        }
        return userDetails;
    }

    protected User getUser(UserDetails userDetails) {
        User user = null;
        String username = userDetails.getUsername();
        if (userDetails instanceof UserDetailsImpl) {
            UserDetailsImpl userDetailsImpl = (UserDetailsImpl) userDetails;
            user = userDetailsImpl.getUserEntity();
            if (user == null) {
                user = userService.findByUsername(username);
            }
        } else {
            user = userService.findByUsername(username);
        }
        return user;
    }

    @Override
    protected String retrievePassword(Authentication authentication) {

        if (authentication.getPrincipal() instanceof UserDetailsImpl) {
            return ((UserDetailsImpl) authentication.getPrincipal()).getPassword();
        } else {
            if (authentication.getCredentials() == null) {
                return null;
            }
            return authentication.getCredentials().toString();
        }
    }
}
